<template>
    <!-- 开启直播 -->
    <div class="savelive">
        <div v-show="liveFormShow">
            <!-- form表单 -->
            <el-form :model="liveForm" ref="liveFrom" :rules="saveLiveRules" label-width="100px" class="demo-ruleForm" style="text-align: left;">
                <el-form-item label="直播封面" >
                    <el-upload
                        class="avatar-uploader"
                        :show-file-list="false"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="直播标题" prop="liveTitle">
                    <el-input v-model="liveForm.liveTitle" style="width: 200px;"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm('liveFrom')">重置</el-button>
                <el-button type="primary" @click="saveLiveFrom('liveFrom')">开启直播</el-button>
            </span>
        </div>
        <div v-show="!liveFormShow">
            <p>服务器地址：{{liveEndity.liveServerUrl}}</p>
            <p>串流密钥：{{liveEndity.streamKey}}</p>
            <p>房间号：{{liveEndity.roomNum}}</p>
            <el-button type="primary" @click="closeLive()">关闭直播</el-button>
        </div>
    </div>
</template>

<script>
export default {
    data () {
        return {
            // 直播表单
            liveForm: {
                id: '',
                // 直播标题
                liveTitle: '',
                // 主播id
                userId: window.sessionStorage.getItem('id'),
            },
            // 图片路径
            imageUrl: '',
            imageFile: File,
            // 直播表单校验规则
            saveLiveRules: {
                liveTitle: [
                    { required: true, message: '请输入直播标题', trigger: 'blur' },
                ],
            },
            // 直播状态
            liveFormShow: true,
            // 直播信息实例
            liveEndity: {}
        }
    },
    mounted () {
        this.getLiveByUserId()
    },
    methods: {
        // 关闭直播
        closeLive () {
            this.$axios.get('/eat-service/live/closeLive', {
                params: {
                    id: this.liveEndity.id
                }
            }).then(res => {
                if (res.data.flag) {
                    this.getLiveByUserId()
                } else {
                    this.myMessage('warning','关闭失败，请稍后重试')
                }
            })
        },
        // 根据用户id获取当前主播是否开播
        getLiveByUserId () {
            this.$axios.get('/eat-service/live/getLiveByUserId', {
                params: {
                    userId: this.liveForm.userId
                }
            }).then(res => {
                if (!res.data.obj) {
                    this.liveFormShow = true
                } else {
                    this.liveEndity = res.data.obj
                    console.log(this.liveEndity)
                    this.liveFormShow = false
                }
            })
        },
        // 上传图片图片校验
		beforeAvatarUpload (file) {
			const isJPG = file.type === 'image/jpeg'
			const isPNG = file.type === 'image/png'
			const isLt2M = file.size / 1024 / 1024 < 2
			if (!isJPG && !isPNG) {
				this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!')
			}
			this.imageUrl = URL.createObjectURL(file)
			this.imageFile = file
			return false
		},
        handleAvatarSuccess (res, file) {
			this.imageUrl = URL.createObjectURL(file.raw)
		},
        // 添加弹窗里的取消按钮 点击取消是清空from表单数据
        resetForm (formName) {
            this.$refs[formName].resetFields()
        },
        saveLiveFrom (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
			        if (this.imageFile.name !== 'File') {
                        // 校验当前主播是否正在直播中
                        this.$axios.get('/eat-service/live/checkLiveByUserId', {
                            params: {
                                userId: this.liveForm.userId
                            }
                        }).then(res => {
                            if (res.data.flag) {
                                this.saveLive()
                            } else {
                                this.myMessage('warning', '当前用户正在直播，无法重复开启直播')
                            }
                        })
                    } else {
                        this.myMessage('warning', '请上传直播封面')
                    }
                }
            })
        },
        // 开启直播 添加直播信息
        saveLive(){
            var formdata = new FormData()
            formdata.set('liveTitle', this.liveForm.liveTitle)
            formdata.set('userId', this.liveForm.userId)
            formdata.set('file', this.imageFile, this.imageFile.name)
            this.$axios.post('/eat-service/live/saveLive', formdata).then(res => {
                if (res.data.flag) {
                    this.getLiveByUserId()
                    // 初始化数据
                    this.liveForm = {
                        liveTitle: '',
                    }
                    this.imageUrl = ''
                    this.imageFile = File
                }
            })
        },
        // 弹窗提示
        myMessage (type, message) {
            this.$message({
                type: type,
                message: message
            })
        }
    }
}
</script>

<style>
.savelive{
    width: 100%;
    height: 100%;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.el-icon-plus:before{
    line-height: 178px;
}
.block {
    text-align: center;
}
</style>